<?php

namespace App\Admin\Forms\Userinfo;

use App\Admin\Models\EmployeeModel;
use Encore\Admin\Widgets\Form;
use Illuminate\Http\Request;
use App\Admin\Models\EmployeeDetailModel;
use Encore\Admin\Facades\Admin;

class Custom extends Form
{
    /**
     * The form title.
     *
     * @var string
     */
    public $title = '自定义信息';

    /**
     * Handle the form request.
     *
     * @param Request $request
     *
     * @return \Illuminate\Http\RedirectResponse
     */
    public function handle(Request $request)
    {
        $data = \Request::input();
        $id   = !empty($data['employee_id']) ? (int)$data['employee_id'] : 0;
        if ($id) {
            $model = EmployeeDetailModel::where('employee_id', '=', $id)->first();
        }
        unset($data['detail_id']);
        if (empty($model)) {
            $result = EmployeeDetailModel::create($data);
        } else {
            $result = $model->update($data);
        }

        if ($result) {
            admin_toastr('保存成功');
        } else {
            admin_toastr('保存失败', 'error');
        }

        return back();
    }

    /**
     * Build a form here.
     */
    public function form()
    {
        $id = $this->getEmployeeId();
        $this->html('<input type="hidden" name="employee_id" value="' . $id . '" class="employee_id">');

        // 自定义内容
        $this->froala('custom_text_zh', __('自定义内容-中文'))->setContentId($id)->setContentType(1)->setWidth(8, 2);
        $this->froala('custom_text_en', __('自定义内容-英文'))->setContentId($id)->setContentType(1)->setWidth(8, 2);
    }

    /**
     * The data of the form.
     *
     * @return array $data
     */
    public function data()
    {
        $id = $this->getEmployeeId();

        $data = EmployeeDetailModel::where('employee_id', '=', $id)->first();
        if (empty($data)) {
            return [];
        }

        return $data->toArray();
    }

    /**
     * 获取员工ID
     *
     * @return int
     */
    private function getEmployeeId()
    {
        $employee = EmployeeModel::select(['employee_id'])->where('user_id', '=', Admin::user()->id)->first();
        if (!$employee) {
            return 0;
        }

        $employee = $employee->toArray();
        return $employee['employee_id'];
    }
}
